﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using System.Web.Mvc;

namespace WroxViewEngine
{
    public class WroxView: IView
    {
        public string ViewPath { get; private set; }
        public string MasterPath { get; private set; }

        public WroxView(string viewPath): this(viewPath, null)
        {
        }

        public WroxView(string viewPath, string masterPath)
        {
            ViewPath = viewPath;
            MasterPath = masterPath;
        }

        private VirtualPathProvider _vpp;

        public VirtualPathProvider VPP
        {
            get
            {
                if (_vpp == null)
                {
                    _vpp = HostingEnvironment.VirtualPathProvider;
                }
                return _vpp;
            }
            set
            {
                _vpp = value;
            }
        }
 


        public void Render(ViewContext viewContext, TextWriter writer)
        {

            Stream virtualFileStream = VPP.GetFile(ViewPath).Open();
            StreamReader reader = new StreamReader(virtualFileStream);
            string template = reader.ReadToEnd();
            
            foreach (KeyValuePair<string, object> valuePair in viewContext.ViewData)
            {
                template = template.Replace("w[" + valuePair.Key + "]", valuePair.Value.ToString());
            }
            writer.Write(template);
        }
    }
}
